<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="itemSpan">
        <el-select
          :key="this.provinceList[0].name"
          v-model="provinceIndex"
          placeholder="省"
          @change="provChange(provinceIndex)"
        >
          <el-option
            v-for="(item,index) in provinceList"
            :key="item.code"
            :label="item.name"
            :value="index"
          ></el-option>
        </el-select>
      </el-col>
      <el-col :span="itemSpan">
        <el-select
          :key="this.townList[0].name"
          v-model="townIndex"
          placeholder="市"
          @change="townChange(townIndex)"
        >
          <el-option
            v-for="item,index in townList"
            :key="item.code"
            :label="item.name"
            :value="index"
          ></el-option>
        </el-select>
      </el-col>
      <el-col :span="8" v-if="level === 3">
        <el-select :key="this.countyList[0].name" v-model="countyIndex" placeholder="县">
          <el-option
            v-for="item,index in countyList"
            :key="item.code"
            :label="item.name"
            :value="index"
          ></el-option>
        </el-select>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 返回值应该为数组[pname, tname,[cname]]
//
export default {
    props: {
        //  默认为 2 省市  可选 3 省市县
        level: {
            type: Number,
            default: 2,
        },
        // v-model
        cityName: {
            // type: Array,
            default: () => [],
        },
    },
    model: {
        prop: 'cityName',
        event: 'cityChange',
    },
    created() {
        var cityDate = localStorage.getItem('cityDate');
        var now = +new Date();
        var expire = parseInt((now - cityDate) / 1000 / 3600 / 24);
        var city = localStorage.getItem('city');

        if (expire < 7 && city) {
            this.cityList = JSON.parse(city);
            this.provinceList = this.cityList;
            // this.townList = this.cityList[0].children;
            // this.countyList = this.cityList[0].children[0].children;
            this.haveData = true;
        } else {
            this.$api.get(
                '/data/city',
                null,
                res => {
                    this.cityList = res;
                    this.provinceList = this.cityList;
                    // this.townList = this.cityList[0].children;
                    // this.countyList = this.cityList[0].children[0].children;
                    this.haveData = true;
                    localStorage.setItem('city', JSON.stringify(res));
                    localStorage.setItem('cityDate', +new Date());
                },
                err => {
                    this.$message.error('获取城市列表失败！');
                }
            );
        }
    },
    data() {
        return {
            haveData: false,
            cityList: [{ children: [{ children: [{}] }] }],
            provinceList: [{}],
            townList: [{}],
            countyList: [{}],
            provinceIndex: '',
            townIndex: '',
            countyIndex: '',
            itemSpan: this.level === 2 ? 12 : 8,
        };
    },
    methods: {
        provChange(index) {
            this.townList = this.provinceList[index].children || [];
            this.countyList = this.townList[0].children || [];
            this.townIndex = 0;
            if (this.countyIndex) {
                this.countyIndex = 0;
            }
        },
        townChange(index) {
            this.countyList = this.townList[index].children || [];
            if (this.countyIndex) {
                this.countyIndex = 0;
            }
        },
        // 将绑定值渲染到组件上
        updateCom() {
            if (typeof this.cityName === 'object') {
                var pname = this.cityName[0];
                var tname = this.cityName[1];
                var cname = this.cityName[2];
                this.provinceIndex = this.cityList.findIndex(item => {
                    return item.name === pname;
                });
                if (this.provinceIndex > -1 && tname) {
                    this.townList = this.cityList[this.provinceIndex].children;
                    this.townIndex = this.townList.findIndex(item => {
                        return item.name === tname;
                    });
                }
                if (this.townIndex > -1 && cname) {
                    this.countyList = this.townList[this.townIndex].children;
                    this.countyIndex = this.countyList.findIndex(item => {
                        return (item.name = cname);
                    });
                }
            }
        },
    },
    computed: {
        // 全部的名称
        cityNameStr() {
            var res;
            this.provinceName && (res = [this.provinceName]);
            this.towName && res.push(this.towName);
            // 是否返回区县名称
            this.level === 3 && this.countyName && res.push(this.countyName);
            return res;
        },
        // 省名称
        provinceName() {
            var obj = '';
            if (this.provinceIndex !== '') {
                var cur = this.provinceList[this.provinceIndex];
                cur && (obj = cur.name);
            }

            return obj;
        },
        // 市名称
        towName() {
            var res = '';
            if (this.townIndex !== '') {
                var cur = this.townList[this.townIndex];
                cur && (res = cur.name);
            }
            return res;
        },
        // 县/区名称
        countyName() {
            var res = '';
            if (this.countyIndex !== '') {
                var cur = this.countyList[this.countyIndex];
                cur && (res = cur.name);
            }
            return res;
        },
    },
    watch: {
        haveData(n) {
            if (n) {
                // model的值有值的时候进行数据还原
                this.updateCom();
            }
        },
        cityNameStr(newValue, oldValue) {
            if (newValue !== oldValue) {
                this.$emit('cityChange', this.cityNameStr);
            }
        },
    },
    updated(){
      console.log("tyui")
    }
};
</script>